package com.fare.taluo.ftp.channel;

import java.io.File;
import java.util.Properties;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.fare.taluo.ftp.DownloadStatus;
import com.fare.taluo.ftp.FTPService;
import com.fare.taluo.ftp.FtpConfiguration;
import com.fare.taluo.ftp.UploadStatus;
import com.fare.taluo.ftp.exception.FTPDownloadException;
import com.fare.taluo.ftp.exception.FTPUploadException;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
/**
 * sftp连接上传下载文件
 * @author creator: xiangsf
 * @author modifior: xiangsf
 * @since 2012-12-27-下午3:22:56
 * @version v1.0
 */
public class SFTPChannel implements FTPService{

	private Session session = null;
	private ChannelSftp channel = null;
	private FtpConfiguration ftpConfig;
	protected static final Logger LOG = Logger.getLogger(SFTPChannel.class
			.getName());

	public SFTPChannel(FtpConfiguration ftpConfig) throws JSchException {
		this.ftpConfig = ftpConfig;
		this.createChannel(60000);
	}

	private void createChannel(int timeout) throws JSchException {
		
		JSch jsch = new JSch(); // 创建JSch对象
		session = jsch.getSession(ftpConfig.getUsername(),
				ftpConfig.getFtpHost(), ftpConfig.getFtpPort()); // 根据用户名，主机ip，端口获取一个Session对象
		if (LOG.isDebugEnabled()) {
			LOG.debug("Session created.");
		}
		if (StringUtils.isNotEmpty(ftpConfig.getPassword())) {
			session.setPassword(ftpConfig.getPassword()); // 设置密码
		}
		Properties config = new Properties();
		config.put("StrictHostKeyChecking", "no");
		session.setConfig(config); // 为Session对象设置properties
		session.setTimeout(timeout); // 设置timeout时间
		session.connect(); // 通过Session建立链接
		if (LOG.isDebugEnabled()) {
			LOG.debug("Session connected.");
		}
		if (LOG.isDebugEnabled()) {
			LOG.debug("Opening Channel.");
		}
		channel = (ChannelSftp)session.openChannel("sftp"); // 打开SFTP通道
		channel.connect(); // 建立SFTP通道的连接
		
		if (LOG.isDebugEnabled()) {
			LOG.debug("Connected successfully to ftpHost = "
					+ ftpConfig.getFtpHost() + ",as ftpUserName = "
					+ ftpConfig.getUsername() + ", returning: " + channel);
		}
	}

	public void disconnect() throws Exception {
		if (channel != null) {
			channel.disconnect();
		}
		if (session != null) {
			session.disconnect();
		}
	}

	@Override
	public DownloadStatus downloadFile(String[] remoteFile, String localDir)
			throws FTPDownloadException {
		String realLocalDir = null;
		try {
			realLocalDir = StringUtils.isNotEmpty(localDir) ? localDir : ftpConfig.getLocaldir();
			for(String file : remoteFile){
				this.channel.get(file, realLocalDir);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new FTPDownloadException(e.getMessage());
		}finally{
			this.channel.quit();
			realLocalDir =null;
		}
		return DownloadStatus.Download_New_Success;
	}

	@Override
	public DownloadStatus downloadFilesInDir(String remoteDir, String localDir)
			throws FTPDownloadException {
		
		LOG.error("暂不支持目录下载！");
		
		return DownloadStatus.Download_New_Failed;
	}

	@Override
	public UploadStatus uploadFile(String[] localFile, String remoteDir)
			throws FTPUploadException {
		String realRemoteDir = null;
		String filename = null;
		try {
			realRemoteDir = StringUtils.isNotEmpty(remoteDir) ? remoteDir : ftpConfig.getRemotedir();
			realRemoteDir = realRemoteDir.endsWith(File.separator) ? realRemoteDir : realRemoteDir+"/";
			for(String file : localFile){
				filename = realRemoteDir+file.substring(file.lastIndexOf(File.separator)+1);
				this.channel.put(file,
						new String(
								filename.getBytes(this.ftpConfig.getDefaultLocalCharset()),
						this.ftpConfig.getDefaultRemoteCharset()), 
						ChannelSftp.OVERWRITE);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new FTPUploadException(e.getMessage());
		}finally{
			this.channel.quit();
			realRemoteDir = null;
			filename = null;
		}
		return UploadStatus.Upload_New_File_Success;
	}

}
